from PySide6.QtWidgets import *
from PySide6.QtGui import *
from PySide6.QtCore import *
import sys

class TaskManagerApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("任务管理器 - QListView 完整示例")
        self.setGeometry(100, 100, 800, 600)
        
        # 初始化数据
        self.tasks = ["阅读邮件", "编写报告", "参加会议", "代码审查", "项目规划"]
        self.init_ui()
        
    def init_ui(self):
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 创建模型和视图
        self.model = QStringListModel(self.tasks)
        self.list_view = QListView()
        self.list_view.setModel(self.model)
        
        # 设置视图属性
        self.list_view.setSelectionMode(QListView.ExtendedSelection)
        self.list_view.setAlternatingRowColors(True)
        self.list_view.setSpacing(2)
        
        # 创建按钮区域
        button_layout = QHBoxLayout()
        
        # 添加任务按钮
        self.add_btn = QPushButton("添加任务")
        self.add_btn.clicked.connect(self.add_task)
        
        # 删除任务按钮
        self.delete_btn = QPushButton("删除选中")
        self.delete_btn.clicked.connect(self.delete_tasks)
        
        # 清空按钮
        self.clear_btn = QPushButton("清空所有")
        self.clear_btn.clicked.connect(self.clear_tasks)
        
        # 完成按钮
        self.complete_btn = QPushButton("标记完成")
        self.complete_btn.clicked.connect(self.mark_completed)
        
        button_layout.addWidget(self.add_btn)
        button_layout.addWidget(self.delete_btn)
        button_layout.addWidget(self.clear_btn)
        button_layout.addWidget(self.complete_btn)
        
        # 搜索区域
        search_layout = QHBoxLayout()
        self.search_edit = QLineEdit()
        self.search_edit.setPlaceholderText("搜索任务...")
        self.search_edit.textChanged.connect(self.filter_tasks)
        search_layout.addWidget(QLabel("搜索:"))
        search_layout.addWidget(self.search_edit)
        
        # 状态显示
        self.status_label = QLabel("总任务数: 0 | 选中: 0")
        
        # 添加到主布局
        main_layout.addLayout(search_layout)
        main_layout.addWidget(self.list_view)
        main_layout.addLayout(button_layout)
        main_layout.addWidget(self.status_label)
        
        # 连接信号
        self.list_view.selectionModel().selectionChanged.connect(self.update_status)
        self.model.dataChanged.connect(self.update_status)
        
        self.update_status()
        
        # 添加上下文菜单
        self.setup_context_menu()
        
    def setup_context_menu(self):
        self.list_view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.list_view.customContextMenuRequested.connect(self.show_context_menu)
        
    def show_context_menu(self, position):
        menu = QMenu()
        
        edit_action = menu.addAction("编辑任务")
        complete_action = menu.addAction("标记完成")
        menu.addSeparator()
        delete_action = menu.addAction("删除任务")
        
        action = menu.exec(self.list_view.mapToGlobal(position))
        
        if action == edit_action:
            self.edit_task()
        elif action == complete_action:
            self.mark_completed()
        elif action == delete_action:
            self.delete_tasks()
    
    def add_task(self):
        text, ok = QInputDialog.getText(self, "添加任务", "请输入任务内容:")
        if ok and text:
            # 获取当前行数
            row = self.model.rowCount()
            self.model.insertRow(row)
            index = self.model.index(row)
            self.model.setData(index, text)
    
    def edit_task(self):
        indexes = self.list_view.selectedIndexes()
        if indexes:
            index = indexes[0]
            old_text = self.model.data(index, Qt.DisplayRole)
            text, ok = QInputDialog.getText(self, "编辑任务", "修改任务内容:", text=old_text)
            if ok and text:
                self.model.setData(index, text)
    
    def delete_tasks(self):
        indexes = self.list_view.selectedIndexes()
        if indexes:
            reply = QMessageBox.question(self, "确认删除", 
                                        f"确定要删除选中的 {len(indexes)} 个任务吗?",
                                        QMessageBox.Yes | QMessageBox.No)
            if reply == QMessageBox.Yes:
                # 需要从后往前删除，避免索引变化
                rows = sorted([index.row() for index in indexes], reverse=True)
                for row in rows:
                    self.model.removeRow(row)
    
    def clear_tasks(self):
        if self.model.rowCount() > 0:
            reply = QMessageBox.question(self, "确认清空", 
                                        "确定要清空所有任务吗?",
                                        QMessageBox.Yes | QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.model.removeRows(0, self.model.rowCount())
    
    def mark_completed(self):
        indexes = self.list_view.selectedIndexes()
        for index in indexes:
            text = self.model.data(index, Qt.DisplayRole)
            if not text.startswith("✅ "):
                self.model.setData(index, "✅ " + text)
    
    def filter_tasks(self, text):
        if not text:
            # 显示所有任务
            self.model.setStringList(self.tasks)
        else:
            # 过滤任务
            filtered = [task for task in self.tasks if text.lower() in task.lower()]
            self.model.setStringList(filtered)
    
    def update_status(self):
        total = self.model.rowCount()
        selected = len(self.list_view.selectedIndexes())
        self.status_label.setText(f"总任务数: {total} | 选中: {selected}")
        
        # 更新原始任务列表（过滤时不影响原始数据）
        if not self.search_edit.text():
            self.tasks = [self.model.data(self.model.index(i), Qt.DisplayRole) 
                         for i in range(total)]

def main():
    app = QApplication(sys.argv)
    
    # 设置应用程序样式
    app.setStyle("Fusion")
    
    # 创建主窗口
    window = TaskManagerApp()
    window.show()
    
    sys.exit(app.exec())

if __name__ == "__main__":
    main()